#ifndef TCPCONNECTION_H
#define TCPCONNECTION_H

#include "../global.h"
#include <boost/asio.hpp>
#include <boost/function.hpp>

class AsyncService;

class TcpConnection : protected boost::noncopyable
{
public:
    typedef boost::asio::ip::tcp::socket Socket;
    typedef boost::asio::ip::tcp::endpoint Endpoint;
    typedef boost::system::error_code ErrorCode;

    typedef boost::function< size_t (size_t) > Filter;
    typedef boost::function< void (size_t, int) > Completion;

public:
    TcpConnection(AsyncService &service);
    ~TcpConnection();

    Socket &sock();

    void close();

    int localEndpoint(std::string &host, unsigned short &port);

    int remoteEndpoint(std::string &host, unsigned short &port);

    void read(void *buf, size_t size,
              BOOST_ASIO_MOVE_ARG(Filter) f,
              BOOST_ASIO_MOVE_ARG(Completion) c);

    void write(const void *buf, size_t size,
               BOOST_ASIO_MOVE_ARG(Filter) f,
               BOOST_ASIO_MOVE_ARG(Completion) c);

protected:
    size_t isComplete(Filter f, ErrorCode ec, size_t size);

    void onComplete(Completion c, ErrorCode ec, size_t size);

private:
    Socket m_sock;
};

#endif // TCPCONNECTION_H
